package com.tryee.wx.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.json.JSONUtil;
import com.tryee.wx.config.utils.WxUtils;
import com.tryee.wx.pojo.DataBean;
import com.tryee.wx.pojo.MiniprogramBean;
import com.tryee.wx.pojo.TemplatePostData;
import com.tryee.wx.pojo.WxTemplateMsg;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.tryee.common.annotation.Log;
import com.tryee.common.enums.BusinessType;
import com.tryee.wx.domain.User;
import com.tryee.wx.service.IUserService;
import com.tryee.framework.web.base.BaseController;
import com.tryee.common.page.TableDataInfo;
import com.tryee.common.base.AjaxResult;
import com.tryee.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信用户 信息操作处理
 *
 * @author tryee
 * @date 2019-03-28
 */
@Controller
@RequestMapping("/wx/user")
public class UserController extends BaseController {

    @Autowired
    private WxUtils wxUtils;

    private String prefix = "wx/user";

    @Autowired
    private IUserService userService;

    @RequiresPermissions("wx:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    /**
     * 查询微信用户列表
     */
    @RequiresPermissions("wx:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user) {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }


    /**
     * 导出微信用户列表
     */
    @RequiresPermissions("wx:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user) {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "user");
    }

    /**
     * 新增微信用户
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存微信用户
     */
    @RequiresPermissions("wx:user:add")
    @Log(title = "微信用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(User user) {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改微信用户
     */
    @GetMapping("/edit/{id}")

    public String edit(@PathVariable("id") Integer id, ModelMap mmap) {
        User user = userService.selectUserById(id);
        mmap.put("user", user);
        return prefix + "/edit";
    }

    /**
     * 修改保存微信用户
     */
    @RequiresPermissions("wx:user:edit")
    @Log(title = "微信用户", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(User user) {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除微信用户
     */
    @RequiresPermissions("wx:user:remove")
    @Log(title = "微信用户", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(userService.deleteUserByIds(ids));
    }


    /**
     * 跳转模板消息页面
     */
    @Log(title = "微信用户", businessType = BusinessType.DELETE)
    @GetMapping("/sendTemplateMsg")
    public String sendTemplateMsg(String openStrs, ModelMap mmp) {
        //获取模板列表
        List<WxTemplateMsg> templates = wxUtils.getTemplates();

        mmp.put("openStrs", openStrs);
        mmp.put("templates", templates);
        return prefix + "/sendTemplateMsg";
    }

    /**
     * 发送模板消息
     */
    @Log(title = "发送模板消息", businessType = BusinessType.DELETE)
    @PostMapping("/toSendTemplateMsg")
    @ResponseBody
    public AjaxResult toSendTemplateMsg(String openStrs, String templateId, String first,
                                        String keyword1, String keyword2, String keyword3,
                                        String remark, String appid, String pagepath, String url) {

        TemplatePostData templatePostData = new TemplatePostData();


        //设置是否跳转小程序
        MiniprogramBean miniprogram = new MiniprogramBean(appid, pagepath);
        templatePostData.setMiniprogram(miniprogram);


        //设置数据 默认颜色为#173177
        DataBean firstBean = new DataBean(first);
        DataBean keyword1Bean = new DataBean(keyword1);
        DataBean keyword2Bean = new DataBean(keyword2);
        DataBean keyword3Bean = new DataBean(keyword3);
        DataBean remarkBean = new DataBean(remark);

        //封装自定义数据
        Map<String, DataBean> map = new HashMap<>();
        map.put("first", firstBean);
        map.put("keyword1", keyword1Bean);
        map.put("keyword2", keyword2Bean);
        map.put("keyword3", keyword3Bean);
        map.put("remark", remarkBean);
        templatePostData.setData(map);


        templatePostData.setTemplate_id(templateId);
        templatePostData.setUrl(url);

        String[] arrStrs = openStrs.split(",");
        String result = "";

        if (arrStrs.length != 0) {
            for (int i = 0; i < arrStrs.length; i++) {
                templatePostData.setTouser(arrStrs[i]);

                //发送请求
                String postStr = JSONUtil.toJsonStr(templatePostData);

                result = wxUtils.sendTemplateMsg(postStr);
            }
        }


        if (result.equals("0")) {
            return success("发送成功！");
        } else if (result.equals("43004")) {
            return error("发送失败！该用户已取消关注！");
        } else {
            return error("发送失败！");
        }

    }

}
